﻿using System;
using UniFramework.Actor;
using UniFramework.Battle;
using UnityEngine;

namespace UniFramework.Skill
{
	public enum ESkillState
	{
		None,
		Before,
		After,
		End
	}

	public partial class Skill
	{
		public SkillConfig skillConfig;
		public LogicActor releaser;
		public LogicActor targeter;
		public ESkillState eState;
		private int _curLogicFrame;
		private float _curLogicFrameAccTime;

		public Action<Skill> OnReleaseAfter; //技能释放后摇
		public Action<Skill, bool> OnReleaseSkillEnd; //技能释放结束
		public Func<Skill, bool> SkillEndCondition; //技能结束的条件

		public Skill(int skillId, LogicActor releaser, LogicActor targeter)
		{
			// skillConfig 通过资源管理器进行加载
			this.releaser = releaser;
			this.targeter = targeter;
			eState = ESkillState.None;
		}

		public Skill(LogicActor releaser, LogicActor targeter, SkillConfig skillConfig)
		{
			this.releaser = releaser;
			this.targeter = targeter;
			this.skillConfig = skillConfig;
			eState = ESkillState.None;
		}

		private void OnSkillStart()
		{
			_curLogicFrame = 0;
			_curLogicFrameAccTime = 0;
		}

		private void OnSkillEnd()
		{
			eState = ESkillState.After;
		}

		private void OnSkillAfter()
		{
		}

		public void ReleaseSkill()
		{
			OnSkillStart();
			eState = ESkillState.Before;
		}

		internal void OnLogicFrameUpdate()
		{
			if (eState == ESkillState.None || eState == ESkillState.End) return;
			_curLogicFrame = _curLogicFrame * LogicFrameConfig.logicFrameIntervalMs;
			bool isSkillAfter = eState == ESkillState.Before &&
			                    _curLogicFrameAccTime >= skillConfig.baseSkillConfig.skillSnakeAfterTimeMs;
			if (isSkillAfter) OnSkillAfter();

			#region 子系统驱动

			OnLogicFrameUpdateAnimation();
			OnLogicFrameUpdateBuff();
			OnLogicFrameUpdateEffect();
			OnLogicFrameUpdateAudio();

			#endregion


			bool skillIsEnd = SkillEndCondition != null && (bool)(SkillEndCondition?.Invoke(this));
			if (skillIsEnd) OnSkillEnd();
			++_curLogicFrame;
		}
	}
}